package cn.seocoo.platform.web.controller.common;


import cn.seocoo.platform.common.core.controller.BaseController;
import cn.seocoo.platform.common.core.domain.AjaxResult;
import cn.seocoo.platform.common.utils.StringUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * 文件上传
 * @author zhihl
 */
@RestController
@RequestMapping("/common/upload")
public class FileController extends BaseController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);
	/**支持图片的类型**/
	private String [] types={".jpg",".jpeg",".png",".PNG",".JPG",".JPEG"};

	private String [] fileType={".doc",".docx",".pdf"};

	/**图片保存路径**/
	@Value("${save.api.image.path}")
	private String savePath;

	/**图片访问ip**/
	@Value("${visit.path}")
	private String visitPath ;

	/**允许上传大小**/

	/**视频保存路径 */
    @Value("${save.api.video.path}")
    private String saveVideoPath;

	/**
	 * 文件保存路径
	 */
	@Value("${save.api.document.path}")
	private String saveDocumentPath;



	/**
	 * 新闻图片上传接口
	 */
	@PostMapping("/ImgUpload")
	public AjaxResult singleImgUpload(@RequestParam(value = "file",required = false) MultipartFile file) throws IOException{
		String fileName = "";
		String dbPath = "";
		if(file != null && !file.isEmpty()){
			fileName = file.getOriginalFilename();
			//文件类型
			String type = fileName.substring(fileName.lastIndexOf("."));
			if (Arrays.asList(types).contains(type)){
				FileOutputStream fileOutputStream = null;
				InputStream inputStream = null;
				try{
					//源文件中文乱码导致图片链接指向不到,使用日期
					Calendar cal = Calendar.getInstance();
					fileName = StringUtils.getRandomStringByDate(22)+type;
					String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
					dbPath = "/upload/" +late;
					File fileSourcePath = new File(savePath+dbPath);
					if (!fileSourcePath.exists()) {
						//目录不存在的情况下创建目录
						fileSourcePath.mkdirs();
					}
					fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
					dbPath += "/" + fileName;
					log.info("----------------------->图片保存路径："+dbPath);
					return AjaxResult.success(dbPath);
				}catch (Exception e){
					e.printStackTrace();
					return AjaxResult.error("上传图片异常");
				}finally {
					if (fileOutputStream != null) {
						fileOutputStream.flush();
						fileOutputStream.close();
					}
				}
			}
			return AjaxResult.warn("不允许上传此类型文件");
		}
		return AjaxResult.warn("文件不能为空！");
	}

	/**
	 * 富文本内容图片上传接口
	 */
	@PostMapping("/richtextImgUpload")
	public AjaxResult richtextImgUpload(@RequestParam(value = "file",required = false) MultipartFile file) throws IOException{
		String fileName = "";
		String dbPath = "";

		if(file != null && !file.isEmpty()){
			fileName = file.getOriginalFilename();
			//文件类型
			String type = fileName.substring(fileName.lastIndexOf("."));
			if (Arrays.asList(types).contains(type)){
				InputStream inputStream = null;
				FileOutputStream fileOutputStream = null;
				try{
					Calendar cal = Calendar.getInstance();
					String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
					fileName = StringUtils.getRandomStringByDate(22)+type;
					dbPath = "/upload/" +late;
					File fileSourcePath = new File(savePath+dbPath);
					if (!fileSourcePath.exists()) {
						//目录不存在的情况下创建目录
						fileSourcePath.mkdirs();
					}
					fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
					dbPath += "/" + fileName;
                    log.info("----------------------->富文本图片路径："+visitPath+dbPath);
					return AjaxResult.success(visitPath+dbPath);
				}catch (Exception e){
					e.printStackTrace();
					return AjaxResult.error("上传图片异常");
				}finally {
					if (fileOutputStream != null) {
						fileOutputStream.flush();
						fileOutputStream.close();
					}
				}
			}
			return AjaxResult.warn("不允许上传此类型文件");
		}
		return AjaxResult.warn("文件不能为空！");
	}

    // 文件最大500M
    private static long upload_maxsize = 800 * 1024 * 1024;
    // 文件允许格式
    private static String[] allowFiles = { ".mp4",".MP4", ".flv", ".avi",  ".wmv",".rmvb" };


    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private boolean checkFileType(String fileName) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取文件扩展名
     *
     * @return string
     */
    private String getFileExt(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }

    /**
     * 依据原始文件名生成新文件名
     * @return
     */
    private String getName(String fileName) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.contains(ext)) {
                String newFileName = fileName.substring(0, fileName.lastIndexOf(ext));
                return newFileName;
            }
        }
        return "";
    }

	/**
	 * @Author WuJian
	 * @Description //TODO bootstrap图片上传
	 * @Date 14:27 2019/7/22
	 * @Param [file]
	 * @return cn.seocoo.platform.common.core.domain.AjaxResult
	 **/
	@PostMapping("/bootstrapImgUpload")
	public AjaxResult bootstrapImgUpload(HttpServletRequest request) throws IOException{
		String fileName = "";
		String dbPath = "";
		StringBuilder sb = new StringBuilder();
		HashMap<String,String> map = new HashMap<>();
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> fileList = multipartRequest.getFiles("file");
		try {
			for (MultipartFile file : fileList) {
				if(file != null && !file.isEmpty()){
					fileName = file.getOriginalFilename();
					//文件类型
					String type = fileName.substring(fileName.lastIndexOf("."));
					if (Arrays.asList(types).contains(type)){
						FileOutputStream fileOutputStream = null;
						InputStream inputStream = null;
						//源文件中文乱码导致图片链接指向不到,使用日期
						Calendar cal = Calendar.getInstance();
						fileName = StringUtils.getRandomStringByDate(22)+type;
						String late = String.valueOf(cal.get(Calendar.YEAR)) + (cal.get(Calendar.MONTH) + 1) + cal.get(Calendar.DAY_OF_MONTH);
						dbPath = "/" +late;
						File fileSourcePath = new File(saveDocumentPath +dbPath);
						if (!fileSourcePath.exists()) {
							//目录不存在的情况下创建目录
							fileSourcePath.mkdirs();
						}
						fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
						inputStream = file.getInputStream();
						IOUtils.copy(inputStream, fileOutputStream);
						dbPath += "/" + fileName;
						logger.info("----------------------->图片保存路径："+dbPath);
					}

				}
			}
			String rotayPath = saveDocumentPath+dbPath;
			map.put("path",dbPath);
			map.put("rotayPath",rotayPath);
			return AjaxResult.success(map);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return AjaxResult.warn("系统繁忙！");
	}


	/**
	 * @return cn.seocoo.platform.api.util.JSONResult
	 * @Author L
	 * @Description 不限类型上传
	 * @Date 11:25 上午 2019/11/4
	 * @Param [file]
	 **/
	@PostMapping("/fileUpload")
	public AjaxResult fileUpload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
		String fileName = "";
		String dbPath = "";
		if (file != null && !file.isEmpty()) {
			fileName = file.getOriginalFilename();
			//文件类型
			String type = fileName.substring(fileName.lastIndexOf("."));
			if (true) {
				FileOutputStream fileOutputStream = null;
				InputStream inputStream = null;
				try {
					//源文件中文乱码导致图片链接指向不到,使用日期
					Calendar cal = Calendar.getInstance();
//                    fileName = StringEx.getRandomStringByDate(22) + type;
					String late = String.valueOf(cal.get(Calendar.YEAR)) + String.valueOf(cal.get(Calendar.MONTH) + 1) + String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
					dbPath = "/upload/" + late;
					File fileSourcePath = new File(saveDocumentPath + dbPath);
					if (!fileSourcePath.exists()) {
						//目录不存在的情况下创建目录
						fileSourcePath.mkdirs();
					}
					fileOutputStream = new FileOutputStream(fileSourcePath + "/" + fileName);
					inputStream = file.getInputStream();
					IOUtils.copy(inputStream, fileOutputStream);
					dbPath += "/" + fileName;
					Map map = new HashMap<>();
					map.put("filePath", dbPath);
					map.put("fileName", fileName);
					logger.warn("----------------------->文件保存路径：" + dbPath);
					return AjaxResult.success(map);
				} catch (Exception e) {
					e.printStackTrace();
					return AjaxResult.error("上传文件异常");
				} finally {
					if (fileOutputStream != null) {
						fileOutputStream.flush();
						fileOutputStream.close();
					}
				}
			}
			return AjaxResult.error("不允许上传此类型文件");
		}
		return AjaxResult.error("文件不能为空");
	}
}
